import 'package:dio/dio.dart';

class HttpClass {
  final _dio = Dio();
  // 构造函数的代码会在实例化的时候执行
  HttpClass() {
    // 配置基础地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    // 设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    // 设置请求头
    _dio.options.headers = {'Content-Type': 'application/json'};
    // 设置拦截器
    _dio.interceptors.add(InterceptorsWrapper(
      // 响应拦截器
      onResponse: (response, handler) {
        return handler.next(response);
      },
      // 请求拦截器
      onRequest: (options, handler) {
        // 注入token
        // options.headers['Authorization'] = '123456';
        return handler.next(options);
      },
      onError: (error, handler) {
        return handler.next(error);
      },
    ));
  }
  // 声明一个请求方法
  // 1.声明请求的参数
  Future<dynamic> request({required RequestParamModel requestParam}) async {
    try {
      if (requestParam.method == 'get') {
        final response = await _dio.get(requestParam.url,
            queryParameters: requestParam.params);
        return handleResponse(response);
      } else if (requestParam.method == 'post') {
        final response =
            await _dio.post(requestParam.url, data: requestParam.data);
        return handleResponse(response);
      } else if (requestParam.method == 'put') {
        final response =
            await _dio.put(requestParam.url, data: requestParam.data);
        return handleResponse(response);
      } else if (requestParam.method == 'delete') {
        final response =
            await _dio.delete(requestParam.url, data: requestParam.params);
        return handleResponse(response);
      }
    } catch (e) {
      return handleError(e);
    }
  }

  // 声明一个处理响应结果的方法
  handleResponse(Response response) {
    // 状态码200-300表示成功
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      // 剥离一层数据
      return response.data;
    } else {
      throw Exception('请求失败，状态码：${response.statusCode}');
    }
  }

  // 声明一个处理错误异常的方法(业务错误)
  handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        throw Exception('响应错误，状态码：${error.response?.statusCode}');
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

final httpClass = HttpClass();

// 抽象类：对对象结构进行类型的约束
abstract class RequestParam {
  String get url;
  String? get method;
  Map<String, dynamic>? get params;
  Map<String, dynamic>? get data;
}

// 可以使用类构造出参数的对象
class RequestParamModel implements RequestParam {
  @override
  final String url;
  @override
  final String? method;
  @override
  final Map<String, dynamic>? params;
  @override
  final Map<String, dynamic>? data;
  RequestParamModel({
    required this.url,
    this.method = 'get',
    this.params, // 可选
    this.data, // 可选
  });
}
